package com.kxxnzstdsw.service.impl

import com.kxxnzstdsw.config.Config
import com.kxxnzstdsw.modle.entity.Account
import com.kxxnzstdsw.modle.entity.Metadata
import com.kxxnzstdsw.modle.entity.by
import com.kxxnzstdsw.modle.enums.AccountStatus
import com.kxxnzstdsw.modle.repo.AccountRepository
import com.kxxnzstdsw.modle.repo.MetadataRepository
import com.kxxnzstdsw.service.MetadataService
import com.kxxnzstdsw.utils.transaction
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.babyfish.jimmer.kt.new
import org.casbin.jcasbin.main.Enforcer
import org.koin.core.component.inject

class MetadataServiceImpl : MetadataService {
  private val metadataRepo by inject<MetadataRepository>()
  private val accountRepo by inject<AccountRepository>()
  private val conf by inject<Config>()
  private val enforcer by inject<Enforcer>()


  override fun initApp(): Unit = runBlocking(Dispatchers.IO) {
    transaction { conn ->
      metadataRepo.saveAll(*conf.versions.map {
        new(Metadata::class).by {
          version = it.version
          log = it.log
        }
      }.toTypedArray(), conn = conn)
      accountRepo.infoByUsername(conf.init.username) ?: accountRepo.save(new(Account::class).by {
        username = conf.init.username
        nikName = conf.init.nikName
        password = conf.init.password
        status = AccountStatus.NORMAL
      }, conn = conn)
      enforcer.addRoleForUser(conf.init.username,"admin")
    }
  }
}
